#include "mainwidget.h"
#include "ui_mainwidget.h"

#include "user.h"
#include <iostream>
#include "tcp_client.h"

#include "user_start_matching.pb.h"
#include "user_stop_matching.pb.h"
#include "network_message.h"

MainWidget::MainWidget(QWidget *parent, std::shared_ptr<tcp_client> client) :
    QWidget(parent),
    ui(new Ui::MainWidget),
    clientPtr_(client)
{
    ui->setupUi(this);

    connect(&timer_, &QTimer::timeout, this, [this]() {
        seconds_++;
        ui->matchingTimeLabel->setText(QString::number(seconds_));
    });

    /* 开始匹配按钮 */
    connect(ui->matchingButton, &QPushButton::clicked, this, [this]() {
        User &user = User::getInstance();
        if (user.userStatus() == User::GAMEING) {
            std::cout << "玩家正在游戏中，无法参与或退出匹配" << std::endl; 
            return;
        }

        if (isMatching_) {
            /* 玩家在匹配中时，点击按钮动作为停止匹配 */
            UserStopMatcingC2SProto user_stop_matching_c2s_proto;
            user_stop_matching_c2s_proto.set_uid(User::getInstance().uid());

            network_message msg(MSG_TYPE_C2S_STOP_MATCHING, user_stop_matching_c2s_proto.SerializeAsString());
            clientPtr_->send_message(msg.to_string());
            timer_.stop();
            ui->matchingButton->setText("开始匹配");
            /* 注：此处没有将is_matching改为false，在收到服务器端返回的停止匹配成功消息后再将is_matching改为false */

        } else {
            UserStartMatchingC2SProto user_start_matching_c2s_proto;
            user_start_matching_c2s_proto.set_uid(User::getInstance().uid());

            network_message msg(MSG_TYPE_C2S_START_MATCHING, user_start_matching_c2s_proto.SerializeAsString());
            clientPtr_->send_message(msg.to_string());
            timer_.start(1000);
            ui->matchingButton->setText("匹配中，点击停止匹配");
            /* 注：此处没有将is_matching改为false，在收到服务器端返回的停止匹配成功消息后再将is_matching改为false */
        }
    });

    connect(this, &MainWidget::hideWindow, this, [this]() {
        this->hide();
    });
}

MainWidget::~MainWidget()
{
    delete ui;
}

QPushButton &MainWidget::matchingButton()
{
    return *ui->matchingButton;
}

void MainWidget::setIsMatching(bool isMatching)
{
    isMatching_ = isMatching;
    // ui->matchingButton->setText(isMatching_ ? "匹配中，点击停止匹配" : "开始匹配");
    if (isMatching_) {
        seconds_ = 0;
    } else {
        seconds_ = 0;
        ui->matchingTimeLabel->setText(QString::number(seconds_));
    }
}

void MainWidget::closeEvent(QCloseEvent *event)
{
    /* 关闭窗口时，停止匹配 */
    if (isMatching_) {
        UserStopMatcingC2SProto user_stop_matching_c2s_proto;
        user_stop_matching_c2s_proto.set_uid(User::getInstance().uid());

        network_message msg(MSG_TYPE_C2S_STOP_MATCHING, user_stop_matching_c2s_proto.SerializeAsString());
        clientPtr_->send_message(msg.to_string());
    }

    QWidget::closeEvent(event);
}
